package com.meizhao.api.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.HashMap;
import java.util.Map;


public final class ResultUtils {

    private static final MessageSource messageSource = (MessageSource) SpringContextUtils.getBean("messageSource");

    public static Map<String, Object> result(ResultCode resultCode, Object data, Object[] args, String msg){
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", resultCode.getCode());
        result.put("data", data);
        result.put("msg", StringUtils.isBlank(msg) ? getMsg(resultCode.getMsg(), args) : getMsg(msg, args));
        return result;
    }

    public static Map<String, Object> result(ResultCode resultCode, Object data, String msg){
        return result(resultCode,data,null,msg);
    }

    private static String getMsg(String msg){
        return getMsg(msg, null);
    }

    private static String getMsg(String msg, Object[] objs){
        try {
            return messageSource.getMessage(msg, objs, LocaleContextHolder.getLocale());
        }catch (NoSuchMessageException e){
            return msg;
        }
    }

    public static Map<String, Object> success(Object data, String msg){

        return result(ResultCode.SUCCESS, data, msg);
    }

    public static Map<String, Object> success(String msg){

        return result(ResultCode.SUCCESS, null, msg);
    }

    public static Map<String, Object> success(Object data){

        return result(ResultCode.SUCCESS, data, null);
    }

    public static Map<String, Object> success(){

        return result(ResultCode.SUCCESS, null, null);
    }

    public static Map<String, Object> failed(String msg){

        return result(ResultCode.FAILED, null,msg);
    }



}
